//
//  LBFileUtil.m
//  LBFoundation
//
//  Created by lhhu on 2020/11/30.
//

#import "LBFileUtil.h"

@implementation LBFileUtil


+ (BOOL)fileExistsAtPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = NO;
    return [fileManager fileExistsAtPath:path isDirectory:&isDirectory] && !isDirectory;
}

+ (BOOL)folderExistsAtPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = NO;
    return [fileManager fileExistsAtPath:path isDirectory:&isDirectory] && isDirectory;
}

+ (BOOL)createDirectoryAtPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if (!isDir && existed) {
        return NO;
    }
    
    if (!(isDir == YES && existed == YES)) {
        return [fileManager createDirectoryAtPath:path
                      withIntermediateDirectories:YES
                                       attributes:nil
                                            error:nil];
    }
    
    return YES;
}

+ (BOOL)createEmptyFileAtPath:(NSString *)path {
    if ([self fileExistsAtPath:path]) {
        return YES;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager createFileAtPath:path
                                contents:nil
                              attributes:nil];
}

+ (BOOL)removeFileAtPath:(NSString *)path {
    if ([self folderExistsAtPath:path]) {
        return NO;
    }
    if (![self fileExistsAtPath:path]) {
        return YES;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager removeItemAtPath:path
                                   error:nil];
}

+ (BOOL)removeFolderAtPath:(NSString *)path {
    if ([self fileExistsAtPath:path]) {
        return NO;
    }
    if (![self folderExistsAtPath:path]) {
        return YES;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager removeItemAtPath:path
                                   error:nil];
}

+ (BOOL)copyFile:(NSString *)path
              to:(NSString *)destPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    [fileManager copyItemAtPath:path
                         toPath:destPath
                          error:&error];
    return error == nil;
}


@end
